

package com.hazelcast.jet.impl.operation;

import com.hazelcast.jet.impl.JetServiceBackend;
import com.hazelcast.jet.impl.execution.ExecutionContext;
import com.hazelcast.jet.impl.execution.init.JetInitDataSerializerHook;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;

import java.io.IOException;
import java.util.concurrent.CompletableFuture;

import static com.hazelcast.jet.Util.idToString;

public class SnapshotPhase2Operation extends AsyncJobOperation {

    private long executionId;
    private long snapshotId;
    private boolean success;

    // for deserialization
    public SnapshotPhase2Operation() {
    }

    public SnapshotPhase2Operation(long jobId, long executionId, long snapshotId, boolean success) {
        super(jobId);
        this.executionId = executionId;
        this.snapshotId = snapshotId;
        this.success = success;
    }

    @Override
    protected CompletableFuture<Void> doRun() {
        JetServiceBackend service = getJetServiceBackend();
        ExecutionContext ctx = service.getJobExecutionService().assertExecutionContext(getCallerAddress(), jobId(), executionId, getClass().getSimpleName());
        assert !ctx.isLightJob() : "snapshot phase 2 started on a light job: " + idToString(executionId);

        return ctx.beginSnapshotPhase2(snapshotId, success).whenComplete((r, t) -> {
            if (t != null) {
                getLogger().warning(String.format("Snapshot %d phase 2 for %s finished with an error on member: %s", snapshotId, ctx.jobNameAndExecutionId(), t), t);
            } else {
                getLogger().fine("Snapshot %s phase 2 for %s finished successfully on member", snapshotId, ctx.jobNameAndExecutionId());
            }
        });
    }

    @Override
    public int getClassId() {
        return JetInitDataSerializerHook.SNAPSHOT_PHASE2_OPERATION;
    }

    @Override
    protected void writeInternal(ObjectDataOutput out) throws IOException {
        super.writeInternal(out);
        out.writeLong(executionId);
        out.writeLong(snapshotId);
        out.writeBoolean(success);
    }

    @Override
    protected void readInternal(ObjectDataInput in) throws IOException {
        super.readInternal(in);
        executionId = in.readLong();
        snapshotId = in.readLong();
        success = in.readBoolean();
    }
}

